package com.example;

import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class MajorDialogController {
    @FXML private TextField nameField;
    @FXML private TextArea descriptionField;
    @FXML private javafx.scene.control.ComboBox<Department> departmentComboBox;

    private Stage dialogStage;
    private Major major;
    private Department department;
    private boolean confirmed = false;

    public void setDialogStage(Stage dialogStage) {
        this.dialogStage = dialogStage;
    }

    public void setMajor(Major major) {
        this.major = major;
        if (major != null) {
            nameField.setText(major.getName());
            descriptionField.setText(major.getDescription());
        }
    }

    public void setDepartment(Department department) {
        this.department = department;
        if (departmentComboBox != null && department != null) {
            departmentComboBox.getSelectionModel().select(department);
        }
    }

    public boolean isConfirmed() {
        return confirmed;
    }

    public Major getMajor() {
        if (major == null) {
            return new Major(0, nameField.getText(), department != null ? department.getId() : 0, descriptionField.getText(), null);
        } else {
            major.setName(nameField.getText());
            major.setDescription(descriptionField.getText());
            if (departmentComboBox != null && departmentComboBox.getValue() != null) {
                major.setDepartmentId(departmentComboBox.getValue().getId());
            }
            return major;
        }
    }

    @FXML
    private void handleConfirm() {
        if (isInputValid()) {
            confirmed = true;
            dialogStage.close();
        }
    }

    @FXML
    private void handleCancel() {
        dialogStage.close();
    }

    private boolean isInputValid() {
        String errorMessage = "";
        if (nameField.getText() == null || nameField.getText().trim().isEmpty()) {
            errorMessage += "专业名称不能为空\n";
        }
        if (errorMessage.length() == 0) {
            return true;
        } else {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("输入错误");
            alert.setHeaderText(null);
            alert.setContentText(errorMessage);
            alert.showAndWait();
            return false;
        }
    }
} 